/*
 * Galaxium Messenger
 * Copyright (C) 2007 Ben Motmans <ben.motmans@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.Collections.Generic;

using Mono.Addins;

using Galaxium.Core;

namespace Galaxium.Protocol
{
	public static class ProtocolUtility
	{
		private static Dictionary<string, IProtocolFactory> _factories;

		static ProtocolUtility ()
		{
			_factories = new Dictionary<string, IProtocolFactory> ();
		}
		
		public static void Initialize ()
		{
			foreach(TypeExtensionNode node in AddinUtility.GetExtensionNodes ("/Galaxium/Protocols"))
			{
				IProtocolFactory factory = (IProtocolFactory)node.CreateInstance();
				
				_factories.Add(factory.Protocol.Name, factory);
			}
		}
		
		public static void Unload ()
		{
		}

		public static IEnumerable<IProtocolFactory> Factories
		{
			get { return _factories.Values; }
		}

		public static IEnumerable<IProtocol> Protocols
		{
			get
			{
				foreach (IProtocolFactory factory in _factories.Values)
					yield return factory.Protocol;
			}
		}
		
		public static IProtocol GetProtocol (string uid)
		{
			ThrowUtility.ThrowIfNull ("uid", uid);

			foreach (IProtocolFactory factory in _factories.Values)
				if (factory.Protocol.Name == uid)
					return factory.Protocol;
			return null;
		}

		public static IProtocolFactory GetProtocolFactory (IProtocol protocol)
		{
			ThrowUtility.ThrowIfNull ("protocol", protocol);

			if (_factories.ContainsKey (protocol.Name))
				return _factories[protocol.Name];
			return null;
		}

		public static IProtocolFactory GetProtocolFactory (string protocol)
		{
			ThrowUtility.ThrowIfNull ("protocol", protocol);

			if (_factories.ContainsKey (protocol))
				return _factories[protocol];
			return null;
		}
	}
}